package chapter7_取消关闭.future取消任务;

import util.ExpUtil;

import java.util.concurrent.*;

public class FutureCancelSnippet {
    private static final ExecutorService taskExec = Executors.newFixedThreadPool(3);

    public static void timeRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException {
        Future<?> task = taskExec.submit(r);
        try {
            task.get(timeout, unit);
        } catch (ExecutionException e) {
            throw ExpUtil.launderThrowable(e);
        } catch (TimeoutException e) {
            // finally中任务将被取消
        } finally {
            // 如果任务已经结束，那么执行取消操作也不会带来任何影响
            task.cancel(true);
        }
    }
}
